package sites.manager.admin.login;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import sites.manager.common.interceptor.LoggedInterceptor;
import sites.manager.common.kit.SiteInfo;

/**
 * 登录
 */
@Clear(LoggedInterceptor.class)
public class LoginController extends Controller {

    @Inject
    LoginService srv;

    /**
     * 跳转至登录页面
     */
    public void index(){
        render("login.html");
    }

    /**
     * 生成验证码
     */
    public void createCaptcha(){
        renderCaptcha();
    }

    /**
     * 登录方法
     */
    @Before(LoginValidator.class)
    public void doLogin() {
        //获取参数
        String userName = getPara("userName", "");
        //获取页面输入的密码
        String password = getPara("password","");

        Ret ret = srv.doLogin(userName, password);
        if(ret.isOk()){//登录成功
            //将当前登录用户保存到session中
            setSessionAttr(SiteInfo.account, ret.get(SiteInfo.account));
            String url = getAttr("ctx")+"/";
            ret.set("url", url);
        }
        renderJson(ret);
    }

    /**
     * 退出登录
     */
    public void logOut(){
        getSession().removeAttribute(SiteInfo.account);
        redirect(getAttr("ctx")+"/login");
    }

}
